package DAO;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

/**
 * @program: wsn_blog
 * @description
 * @author:王松年
 * @creat: 2021-07-11 11:52:17
 **/
public class DBUtil {
    private static volatile DataSource dataSource;
    private static final String URL = "jdbc:mysql://localhost:3306/blog";
    private static final String username = "root";
//    private static final String password = "142857"; //Windows上的密码
    private static final String password = "Wsn142857";//Centos上的密码

    private DBUtil() {
    }

    private static DataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource) dataSource).setUrl(URL);
                    ((MysqlDataSource) dataSource).setUser(username);
                    ((MysqlDataSource) dataSource).setPassword(password);
                    ((MysqlDataSource) dataSource).setUseSSL(false);
                    ((MysqlDataSource) dataSource).setUseUnicode(true);
                    ((MysqlDataSource) dataSource).setCharacterEncoding("utf-8");
                }
            }
        }
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    public static void close(Connection connection, PreparedStatement statement) throws SQLException {
        close(connection, statement, null);
    }
}
